package com.yc.cloud.openai.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.yc.cloud.basic.exception.Asserts;
import com.yc.cloud.basic.utils.MyFileUtils;
import com.yc.cloud.openai.dto.IATResultDTO;
import com.yc.cloud.openai.dto.resp.HFKJIatResp;
import com.yc.cloud.openai.request.IatParam;
import com.yc.cloud.openai.service.IATService;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.stereotype.Service;

/**
 * 腾讯云语音转文字实现类
 */
@Service("HFKJIatServiceImpl")
@Slf4j
public class HFKJIatServiceImpl implements IATService {
    String apiUrl = "https://saas.hafengkeji.com/ai/api/shuziren/yuyinshibie";

    @Override
    public IATResultDTO getIatResult(IatParam param) {
        val path = param.getContent();
        if (StrUtil.isEmpty(path)) {
            log.error("HFKJIat 请求失败, 文件路径为空");
            return null;
        }
        val base64Data = MyFileUtils.convertToBase64(FileUtil.file(path));
        if (StrUtil.isNotEmpty(base64Data)) {
            // 构建请求体
            String requestBody = JSONUtil.createObj().set("data", base64Data).set("format", param.getFormat()).set("dataLen", base64Data.length()).toString();
            // 发送 POST 请求
            val iatStartTime = System.currentTimeMillis();
            try (HttpResponse response = HttpRequest.post(apiUrl).header("Content-Type", "application/json") // 设置内容类型为 JSON
                    .body(requestBody) // 设置请求体
                    .execute()) {
                val content = response.body();
                val iatEndTime = System.currentTimeMillis();
                log.info("HFKJIat请求返回结果-->{}", content);
                val costTime = iatEndTime - iatStartTime;
                log.info("HFKJIat 语音听写花费{}", costTime);
                val iatResult = JSONUtil.toBean(content, HFKJIatResp.class);
                if (iatResult.getCode() != 0) {
                    log.error("HFKJIat 响应失败,错误信息--->{}", iatResult.getMsg());
                    Asserts.fail(iatResult.getMsg());
                }
                val result = iatResult.getData().getResult();
                log.info("HFKJIat Result--->{}", result);
                val iatResultDTO = new IATResultDTO();
                iatResultDTO.setResult(result);
                iatResultDTO.setCostTime(costTime);
                return iatResultDTO;
            }
        }
        return null;
    }
}
